package sql

import (
	"database/sql"
	"github.com/lexkong/log"
	"strings"
	//引入上面的数据库驱动包之后会自动去调用init函数，然后在init函
	//数里面注册这个数据库驱动，这样我们就可以在接下来的代码中直接使用这个数据库驱动了。
	_ "github.com/go-sql-driver/mysql"
)

func CreateConnection(username string, password string, database string) *sql.DB {
	url := username + ":" + password + "@/" + database + "?charset=utf8&parseTime=true"
	log.Infof(url)
	db, e := sql.Open("mysql", url)
	checkErr(e)
	return db
}

func Insert(db *sql.DB, sql string, params ...interface{}) sql.Result {
	stmt, e := db.Prepare(sql)
	checkErr(e)
	result, e := stmt.Exec(params)
	defer db.Close()
	return result
}

func Update(db *sql.DB, sql string, params ...interface{}) sql.Result {
	stmt, e := db.Prepare(sql)
	checkErr(e)
	result, e := stmt.Exec(params)
	defer db.Close()
	return result
}

func Select(db *sql.DB, sql string, params ...interface{}) (rows *sql.Rows, e error) {
	rows, e = db.Query(sql, params...)
	defer db.Close()
	return rows, e
}

func checkErr(err error) {
	if err != nil {
		panic(err)
	}
}

func Placeholders(n int) string {
	ps := make([]string, n)
	for i := 0; i < n; i++ {
		ps[i] = "?"
	}
	return strings.Join(ps, ",")
}
